package com.spring.courseapi.web.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestParam;

import com.google.common.collect.Lists;
import com.spring.common.web.service.CommonService;
import com.spring.courseapi.web.dao.GameCourseMapper;
import com.spring.courseapi.web.requestModel.Register;
import com.spring.courseapi.web.service.GameService;
import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.web.dao.JedisCache;
import com.spring.security.web.model.BaseResult;
import com.spring.tools.MyTools;
import com.sso.api.web.dao.SsoMapper;
import com.sso.api.web.model.RequestUser;
import com.sso.api.web.model.SsoFamily;

@Service
public class GameServiceImpl implements GameService{

	@Resource
	private JedisCache jedisCache;
	
	@Resource
	private CommonService commonService;	
	
	@Resource
	private SsoMapper ssoMapper;	
		
	@Resource
	private GameCourseMapper gameCourseMapper;	
	
	//注册 
	@Override
	public BaseResult register(Register register,String course_open_detailID) throws Exception {
		List<Map<String,Object>> retM = Lists.newArrayList();
		String familyID=null;
		String phone=null;
		BaseResult ret = new BaseResult("1","注册成功");
		
		BaseResult brc=MyTools.checkIsNotNullBR(course_open_detailID,register.getIsOldUser());
		if(brc!=null){
			return new BaseResult("0","请输入必要参数");
		}
		
		
		if(register.getIsOldUser().equals("0")){
			
		
		//注册监护人
		if(register.getGuardians()!=null){
			for(int i=0;i<register.getGuardians().size();i++){
				RequestUser guardian=register.getGuardians().get(i);
				HashMap<String,Object> hmc=MyTools.checkIsNotNull(guardian.getPhone());
				if(hmc!=null){
					//TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return new BaseResult("0","请输入必要参数");
				}
				phone=guardian.getPhone();
				guardian.setUserName(guardian.getPhone());
				if(i==0){//新建家庭id
					//新增家长信息
					Map<String, Object> hm=commonService.addUser(guardian);
					if(MyTools.ObjectToString(hm.get(ApplicationUtils.STATUS)).equals("0")){
						//TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
						return new BaseResult("0",hm.get(ApplicationUtils.MSG).toString());
					}
					Map<String, Object> dataset=(Map<String, Object>)hm.get(ApplicationUtils.DATASET);
					//回写新增用户信息
					dataset.put("realName",guardian.getReal_name());
					retM.add(dataset);
					
					familyID=MyTools.ObjectToString(dataset.get("c_familyID"));
				}else{//调用第一个新增家长的家庭id
					guardian.setC_family_id(familyID);
					Map<String, Object> hm=commonService.addUser(guardian);
					Map<String, Object> dataset=(Map<String, Object>)hm.get(ApplicationUtils.DATASET);
					//回写新增用户信息
					dataset.put("realName",guardian.getReal_name());
					retM.add(dataset);
				}	
				
			}
		}
		
		if(register.getBabies()!=null){
			//新增宝宝信息
			for(int i=0;i<register.getBabies().size();i++){
				RequestUser baby=register.getBabies().get(i);		
				if(StringUtils.isBlank(baby.getC_family_id())&&StringUtils.isBlank(familyID)){
					continue;
				}
				
				if(StringUtils.isBlank(baby.getC_family_id())){
					baby.setC_family_id(familyID);			
				}
				
				//baby.setSex_code("0");
				baby.setC_role_id("0");
				//宝宝名(real_name)，性别，年龄->必输
				Map<String, Object> hm=commonService.addUser(baby);
				if(MyTools.ObjectToString(hm.get(ApplicationUtils.STATUS)).equals("0")){
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return new BaseResult("0",hm.get(ApplicationUtils.MSG).toString());
				}
				Map<String, Object> dataset=(Map<String, Object>)hm.get(ApplicationUtils.DATASET);
				//回写新增用户信息
				dataset.put("realName",baby.getReal_name());
				retM.add(dataset);
				
				HashMap<String, Object> hm2=new HashMap<String, Object>();
				String c_user_id=MyTools.ObjectToString(dataset.get("c_user_id"));
//				String baby_name=String.valueOf(jsonObject.get("baby_name"));
//				String phone2=String.valueOf(jsonObject.get("phone"));
				hm2.put("c_user_id", c_user_id);
				hm2.put("course_open_detailID", course_open_detailID);
				hm2.put("baby_name", baby.getReal_name());		
				hm2.put("phone", phone);	
				
				if(course_open_detailID!=null){
					int count=gameCourseMapper.appointCourseCheckCount(hm2);			
					if(count>0){
						return new BaseResult("0","请勿重复预约");
					}		
					int effect = gameCourseMapper.courseAppointment(hm2);		
					if(effect<1){
						return new BaseResult("0","预约失败");
					}
				}
			}
		}
		
		ret.setDataset(retM);
		}else{
		//老用户	
	
		   if(register.getGuardians()!=null){
			   RequestUser guardian=register.getGuardians().get(0);
			   //获取家庭id
			    phone=guardian.getPhone();
			   
			   familyID=ssoMapper.getFamilyIDByPhone(phone);	 
			   
			   if(familyID==null||familyID.equals("")){
				   return new BaseResult("0","手机号无效");
			   }
		   }
		   
		   for(int i=0;i<register.getBabies().size();i++){
				RequestUser baby=register.getBabies().get(i);		
				if(StringUtils.isBlank(baby.getC_family_id())&&StringUtils.isBlank(familyID)){
					continue;
				}
				
				if(StringUtils.isBlank(baby.getC_family_id())){
					baby.setC_family_id(familyID);			
				}
				
				//baby.setSex_code("0");
				baby.setC_role_id("0");
				//宝宝名(real_name)，性别，年龄->必输
				Map<String, Object> hm=commonService.addUser(baby);
				if(MyTools.ObjectToString(hm.get(ApplicationUtils.STATUS)).equals("0")){
					return new BaseResult("0",hm.get(ApplicationUtils.MSG).toString());
				}
				Map<String, Object> dataset=(Map<String, Object>)hm.get(ApplicationUtils.DATASET);
				//回写新增用户信息
				dataset.put("realName",baby.getReal_name());
				retM.add(dataset);
				
				HashMap<String, Object> hm2=new HashMap<String, Object>();
				String c_user_id=MyTools.ObjectToString(dataset.get("c_user_id"));
//				String baby_name=String.valueOf(jsonObject.get("baby_name"));
//				String phone2=String.valueOf(jsonObject.get("phone"));
				hm2.put("c_user_id", c_user_id);
				hm2.put("course_open_detailID", course_open_detailID);
				hm2.put("baby_name", baby.getReal_name());		
				hm2.put("phone", phone);	
				
				if(course_open_detailID!=null){
					int count=gameCourseMapper.appointCourseCheckCount(hm2);			
					if(count>0){
						return new BaseResult("0","请勿重复预约");
					}		
					int effect = gameCourseMapper.courseAppointment(hm2);		
					if(effect<1){
						return new BaseResult("0","预约失败");
					}
				}
			}
		   
		   ret.setDataset(retM); 
		   
		}
		
		return ret;
	}
	
	
	@Override
	public BaseResult family(@RequestParam String phone) throws Exception {
		BaseResult br=MyTools.checkIsNotNullBR(phone);
		if(br!=null){
			return br;
		}
		
		HashMap<String,Object> hm=new HashMap<String,Object>();
		hm.put("phone", phone);

		List<SsoFamily> list = ssoMapper.getFamilyDetail(hm);

		return new BaseResult("1","查询成功",list);
	}
	
	
	@Override
	public BaseResult courseAppointment( String course_open_detailID,
			 String babies) throws Exception {
		
		BaseResult br=MyTools.checkIsNotNullBR(course_open_detailID,babies);
		if(br!=null){
			return br;
		}
		
		HashMap<String,Object> hm=new HashMap<String,Object>();
		hm.put("course_open_detailID", course_open_detailID);
		//hm.put("phone", phone);		
		
		JSONArray json = JSONArray.fromObject(babies);
		for (int i = 0; i < json.size(); i++) {
			JSONObject jsonObject = json.getJSONObject(i);
		
			String c_user_id=String.valueOf(jsonObject.get("c_user_id"));
			String baby_name=String.valueOf(jsonObject.get("baby_name"));
			String phone2=String.valueOf(jsonObject.get("phone"));
			hm.put("c_user_id", c_user_id);
			hm.put("baby_name", baby_name);		
			hm.put("phone", phone2);	
			
			BaseResult br2=MyTools.checkIsNotNullBR(c_user_id,baby_name);
			if(br!=null){
				return br2;
			}			
			int count=gameCourseMapper.appointCourseCheckCount(hm);			
			if(count>0){
				return new BaseResult("0","请勿重复预约");
			}		
			int effect = gameCourseMapper.courseAppointment(hm);		
			if(effect<1){
				return new BaseResult("0","预约失败");
			}
		}
	
		return new BaseResult("1","插入成功");
	}
	
	
	
	@Override
	public BaseResult cancelCourseAppointment(String course_open_detailID, String c_user_id) throws Exception {
		
		BaseResult br=MyTools.checkIsNotNullBR(course_open_detailID,c_user_id);
		if(br!=null){
			return br;
		}
		
		HashMap<String,Object> hm=new HashMap<String,Object>();
		hm.put("course_open_detailID", course_open_detailID);
		hm.put("c_user_id", c_user_id);

		
		int effect=gameCourseMapper.cancelCourseAppointment(hm);

		if(effect<1){
			return new BaseResult("0","取消失败");
		}
		
		return new BaseResult("1","取消成功");
	}
	
	@Override
	public BaseResult todayFamily(String skip, String rows) throws Exception {
		
		HashMap<String,Object> hm=MyTools.pageIndexToSkip(null, null, skip, rows);
		String[] userList=gameCourseMapper.todayUser(hm);
		
		if(userList.length==0){
			return new BaseResult("1","查询成功",new ArrayList());
		}
		
		HashMap<String,Object> hm2=new HashMap<String,Object>();
		hm2.put("userList", userList);
		
		List<SsoFamily> list =ssoMapper.getFamilyDetail(hm2);

		return new BaseResult("1","查询成功",list);

	}
}
